package cn.iocoder.yudao.module.wecom.controller.admin.msgsendlog;

import cn.hutool.json.JSONUtil;
import cn.iocoder.yudao.module.wecom.dal.dataobject.chatgroup.WeChatGroupDO;
import cn.iocoder.yudao.module.wecom.dal.dataobject.customer.WeCustomerDO;
import cn.iocoder.yudao.module.wecom.service.chatgroup.WeChatGroupService;
import cn.iocoder.yudao.module.wecom.service.customer.WeCustomerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import javax.validation.constraints.*;
import javax.validation.*;
import javax.servlet.http.*;
import java.util.*;
import java.io.IOException;
import java.util.stream.Collectors;

import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;

import cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog;

import static cn.iocoder.yudao.framework.operatelog.core.enums.OperateTypeEnum.*;

import cn.iocoder.yudao.module.wecom.controller.admin.msgsendlog.vo.*;
import cn.iocoder.yudao.module.wecom.dal.dataobject.msgsendlog.MsgSendLogDO;
import cn.iocoder.yudao.module.wecom.service.msgsendlog.MsgSendLogService;

@Tag(name = "管理后台 - 消息记录")
@RestController
@RequestMapping("/wecom/msg-send-log")
@Validated
@Slf4j
public class MsgSendLogController {

    @Resource
    private MsgSendLogService msgSendLogService;

    @Resource
    private WeCustomerService weCustomerService;

    @Resource
    private WeChatGroupService weChatGroupService;

    @PostMapping("/create")
    @Operation(summary = "创建消息记录")
    @PreAuthorize("@ss.hasPermission('wecom:msg-send-log:create')")
    public CommonResult<Long> createMsgSendLog(@Valid @RequestBody MsgSendLogSaveReqVO createReqVO) {
        return success(msgSendLogService.createMsgSendLog(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新消息记录")
    @PreAuthorize("@ss.hasPermission('wecom:msg-send-log:update')")
    public CommonResult<Boolean> updateMsgSendLog(@Valid @RequestBody MsgSendLogSaveReqVO updateReqVO) {
        msgSendLogService.updateMsgSendLog(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除消息记录")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('wecom:msg-send-log:delete')")
    public CommonResult<Boolean> deleteMsgSendLog(@RequestParam("id") Long id) {
        msgSendLogService.deleteMsgSendLog(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得消息记录")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('wecom:msg-send-log:query')")
    public CommonResult<MsgSendLogRespVO> getMsgSendLog(@RequestParam("id") Long id) {
        MsgSendLogDO msgSendLog = msgSendLogService.getMsgSendLog(id);
        return success(BeanUtils.toBean(msgSendLog, MsgSendLogRespVO.class));
    }

    @GetMapping("/get-send-result")
    @Operation(summary = "获得消息发送结果")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @Parameter(name = "cursor", description = "编号", required = false, example = "")
    @PreAuthorize("@ss.hasPermission('wecom:msg-send-log:query')")
    public CommonResult<MsgSendResultRespVO> getMsgSendResult(@RequestParam("id") Long id, @RequestParam(value = "cursor", required = false) String cursor) {
        MsgSendResultRespVO respVO = msgSendLogService.getMsgSendResult(id, cursor);
        return success(respVO);
    }

    @GetMapping("/page")
    @Operation(summary = "获得消息记录分页")
    @PreAuthorize("@ss.hasPermission('wecom:msg-send-log:query')")
    public CommonResult<PageResult<MsgSendLogRespVO>> getMsgSendLogPage(@Valid MsgSendLogPageReqVO pageReqVO) {
        PageResult<MsgSendLogDO> pageResult = msgSendLogService.getMsgSendLogPage(pageReqVO);
        PageResult<MsgSendLogRespVO> resp = BeanUtils.toBean(pageResult, MsgSendLogRespVO.class);
        resp.getList().forEach(vo -> {
            if (vo.getChatType().equals("single")) {
                List<WeCustomerDO> list = weCustomerService.getCustomerListByWeCustomerIds(vo.getToUserList());
                vo.setToUserNameList(list.stream().map(WeCustomerDO::getName).collect(Collectors.toList()));
            } else {
                List<WeChatGroupDO> list = weChatGroupService.getWeChatGroupListByChatIds(vo.getToUserList());
                vo.setToUserNameList(list.stream().map(WeChatGroupDO::getName).collect(Collectors.toList()));
            }
        });
        return success(resp);
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出消息记录 Excel")
    @PreAuthorize("@ss.hasPermission('wecom:msg-send-log:export')")
    @OperateLog(type = EXPORT)
    public void exportMsgSendLogExcel(@Valid MsgSendLogPageReqVO pageReqVO,
                                      HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<MsgSendLogDO> list = msgSendLogService.getMsgSendLogPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "消息记录.xls", "数据", MsgSendLogRespVO.class,
                BeanUtils.toBean(list, MsgSendLogRespVO.class));
    }

}